package demo.xlj.yuyi.studentapp.retrofit;

import android.content.Context;
import android.text.TextUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import demo.xlj.yuyi.studentapp.utils.NetUtils;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by whstywh on 2017/4/5 0005
 * GitHub：https://github.com/whstywh
 * email：whstywh@163.com
 * description：retrofit的封装
 */

public class RetrofitClient {

    private String TAG = "RetrofitClient";
    private static final long TIMEOUT = 30;//超时时间 30秒
    private static RetrofitClient client;
    private final String baseUrl = "http://www.yuyigufen.com/studentClub/public/index.php/";
    private final OkHttpClient okHttpClient;
    private static ApiService apiService;
    private static Context mContext;
    //缓存文件名称
    private String CACHE_NAME = "zhihuiyuyi";
    //缓存大小
    private int CACHE_SIZE = 10 * 1024 * 1024;

    /***
     * 自定义 Interceptor
     */
    Interceptor mInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetUtils.isConnected(mContext)) {
                request = request.newBuilder()
                        //当没有网络时
                        //CacheControl.FORCE_CACHE; //仅仅使用缓存
                        //CacheControl.FORCE_NETWORK;// 仅仅使用网络
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            Response proceed = chain.proceed(request);

            if (NetUtils.isConnected(mContext)) {
                //有网
                //String cacheControl = request.cacheControl().toString();
                return proceed.newBuilder()
                        //清除头信息
                        .removeHeader("Pragma")
                        //设置缓存时间为0秒，表示总不缓存
                        .header("Cache-Control", "public, max-age=" + 60)
                        .build();
            } else {
                //没网
                int maxTime = 4 * 24 * 60 * 60;//缓存时间：4周
                return proceed.newBuilder()
                        .removeHeader("Pragma")
                        //设置缓存时间为4周，
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxTime)
                        .build();
            }
        }
    };

    public ApiService getApiService() {
        return apiService;
    }

    public static RetrofitClient getInstance(Context context) {
        if (context != null) {
            mContext = context;
        }
        if (client == null) {
            client = new RetrofitClient(context);
        }
        return client;
    }

    public static RetrofitClient getInstance(Context context, String url) {
        if (context != null) {
            mContext = context;
        }
        if (client == null) {
            client = new RetrofitClient(context, url);
        }
        return client;

    }

    public RetrofitClient(Context context) {
        this(context, null);
    }

    public RetrofitClient(Context context, String url) {

        if (TextUtils.isEmpty(url)) {
            url = baseUrl;
        }
        //设置缓存文件
        File file = new File(mContext.getCacheDir(), CACHE_NAME);//缓存文件路径
        Cache cache = new Cache(file, CACHE_SIZE);//缓存文件大小为10MB

        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(mInterceptor)//添加应用拦截器
                .addNetworkInterceptor(mInterceptor)//添加网络拦截器
                .cache(cache)//设置缓存
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)//连接超时 5秒
                .readTimeout(TIMEOUT, TimeUnit.SECONDS)//读取超时时间
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(url)
                .build();
        apiService = retrofit.create(ApiService.class);
    }

}
